package com.hfy.admin.processor;

import annotation.Processor;
import beans.mybatis.user.mapper.PostDataMapper;
import com.hfy.model.po.user.post.PostDataPo;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.hfy.admin.service.PostDailyHeatService;
import com.hfy.model.po.admin.PostDailyHeatPo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import tech.powerjob.official.processors.impl.sql.DynamicDatasourceSqlProcessor;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;
import tech.powerjob.worker.log.OmsLogger;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ author 韩
 * time: 2025/3/5 2:01
 */

@Processor
@Slf4j
public class HeatProcessor implements BasicProcessor {


    @Autowired
    private PostDataMapper postDataMapper;

    @Autowired
    private PostDailyHeatService postDailyHeatService;


    // 写入热度
    @Override
    public ProcessResult process(TaskContext context) throws Exception {

        OmsLogger logger = context.getOmsLogger();
//        LambdaUpdateWrapper<PostDataPo> updateWrapper = Wrappers.lambdaUpdate();
//        updateWrapper.setIncrBy(PostDataPo::getViewNum, 1);
//        int update = postDataMapper.update(updateWrapper);
//        log.info("更新了多少" + update + "条");
        List<PostDataPo> heatList = getHeatList();
//        DynamicDatasourceSqlProcessor
        dropDailyHeat(heatList);
        logger.info("热度更新成功");
        return new ProcessResult(true, "热度更新成功");
    }

    @DS("user")
    public List<PostDataPo> getHeatList() {
        return postDataMapper.getHeatList();
    }


    @DS("admin")
    public void dropDailyHeat(List<PostDataPo> heatList) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        // 写入热度数据
        List<PostDailyHeatPo> dailyHeatList = heatList.stream().map(item -> BeanUtil.toBean(item, PostDailyHeatPo.class).setDate(now)).collect(Collectors.toList());


        postDailyHeatService.saveBatch(dailyHeatList);


    }
}
